package com.sfac.javaSpringBoot.listener;

import com.sfac.javaSpringBoot.modules.test.controller.TestController;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import javax.servlet.ServletContextEvent;
import javax.servlet.ServletContextListener;
import javax.servlet.annotation.WebListener;
import java.io.File;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;

@WebListener
//删除非当日文件
public class LogDestroyListener implements ServletContextListener {
    private final static Logger LOGGER = LoggerFactory.getLogger(LogDestroyListener.class);

    @Override
    public void contextInitialized(ServletContextEvent sce) {
        LOGGER.debug("===========Init Context=============");

        File destFolder=new File("/log");
        if(destFolder==null||!destFolder.exists()){
            return;
        }
        DateTimeFormatter dtf=DateTimeFormatter.ofPattern("yyyy-mm-dd");
        String currentDate = dtf.format(LocalDateTime.now());

        File[] files = destFolder.listFiles();
        for(File file:files){
            String fileName=file.getName();
            if (!fileName.contains(currentDate)){
                file.delete();
            }
        }

    }
    @Override
    public void contextDestroyed(ServletContextEvent sce) {
        LOGGER.debug("===========Destroy Context=============");
    }
}
